package com.solcoo.common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;
import android.util.Log;

import com.solcoo.common.App;
import com.solcoo.common.security.EncryptUtil;

public class FileUtil {
	private static String TAG = "FileUtil";
	private static final String SD_STORAGE_DIR_TAOBAN = "/solcoo";
	private static final String MOBILE_STORAGE_DIR_TAOBAN = "/img";
	private static String mImageCacheDir;
	private static final int CACHE_LENGTH = 300;

	static {
		mImageCacheDir = getImageCacheDir();
	}

	/**
	 * 根据URL从本地Cache目录中获取InputStream
	 * 
	 * @param url
	 * @return
	 */
	public static InputStream getInputStreamByUrl(String url) {
		String md5FileName = EncryptUtil.md5Hex(url);
		return getInputStreamByLocalPath(mImageCacheDir, md5FileName);
	}

	private static InputStream getInputStreamByLocalPath(String path,
			String fileName) {
		File file = new File(path, fileName);
		if (file.exists()) {
			Log.i(TAG,
					"getInputStreamByLocalPath by Path = "
							+ file.getAbsolutePath());
			try {
				InputStream in = new FileInputStream(file);
				return in;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 将URL对应的从服务端取得的数据保持至本地Cache目录中的文件
	 * 
	 * @param url
	 * @param ins
	 */
	public static String saveToLocalFileByUrl(String url, InputStream ins) {
		if (ins == null) {
			return null;
		}

		String md5FileName = EncryptUtil.md5Hex(url);
		File file = new File(mImageCacheDir, md5FileName);
		String path = file.getAbsolutePath();
		FileOutputStream out = null;

		try {
			int read = 0;
			byte[] bytes = new byte[1024];
			out = new FileOutputStream(file);
			while ((read = ins.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			Log.i(TAG, "saveToLocalFileByUrl by Path = " + path);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
			path = StringUtil.EMPTY;
		} finally {
			try {
				ins.close();
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return path;
	}

	/**
	 * 获取存放本地图片的缓存目录，若无SD卡，则放在应用的缓存目录
	 * 
	 * @return
	 */
	public static String getImageCacheDir() {
		String cacheDir = getTaobanDirPath();

		// 判断是否存在SD卡
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			cacheDir = getSdDirPath();
		}
		return cacheDir;
	}

	/**
	 * 获取应用的缓存目录
	 * 
	 * @return
	 */
	public static String getTaobanDirPath() {

		String cacheDir = App.getCacheDir().getAbsolutePath()
				+ MOBILE_STORAGE_DIR_TAOBAN;
		File taobanDir = new File(cacheDir);
		if (!taobanDir.exists()) {
			taobanDir.mkdir();
		}
		return cacheDir;
	}

	/**
	 * 获取SD卡中的淘伴目录
	 * 
	 * @return
	 */
	public static String getSdDirPath() {
		String cacheDir = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + SD_STORAGE_DIR_TAOBAN;
		File taobanDir = new File(cacheDir);
		if (!taobanDir.exists()) {
			taobanDir.mkdir();
		}
		return cacheDir;
	}

	/**
	 * 另起一条线程清除缓存
	 */
	public static void clearCache() {
		final File dir = new File(mImageCacheDir);
		if (!dir.exists()) {
			return;
		}
		new Thread() {
			@Override
			public void run() {
				if (deleteFile(dir)) {// 重新创建该目录
					dir.mkdir();
				}
			};
		}.start();
	}

	/**
	 * 递归删除文件夹
	 * 
	 * @param dir
	 * @return
	 */
	public static boolean deleteFile(File file) {
		if (file.isDirectory()) {
			final String[] children = file.list();// 递归删除目录中的子目录下
			final int length = children.length;
			for (int i = 0; i < length; i++) {
				boolean success = deleteFile(new File(file, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return file.delete();
	}

	/**
	 * 得到缓存目录的大小
	 * 
	 * @return
	 */
	public static int getCacheDirLength() {
		File dir = new File(mImageCacheDir);
		if (!dir.exists()) {
			return 0;
		}
		if (!dir.isDirectory()) {
			return 0;
		}
		return ArrayUtil.getLength(dir.list());
	}

	/**
	 * 是否需要清理缓存
	 * 
	 * @return
	 */
	public static boolean isNeedClear() {
		return getCacheDirLength() > CACHE_LENGTH;
	}

	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		copy(input, output);
		return output.toByteArray();
	}

	public static int copy(InputStream input, OutputStream output)
			throws IOException {
		long count = copyLarge(input, output);
		if (count > 2147483647L) {
			return -1;
		}
		return (int) count;
	}

	public static long copyLarge(InputStream input, OutputStream output)
			throws IOException {
		byte[] buffer = new byte[4096];
		long count = 0L;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

	public static String getImgPath(String fileName) {
		return new StringBuilder(getImageCacheDir()).append("/")
				.append(fileName).toString();
	}

	public static void closeInputStream(InputStream is) {
		try {
			if (is != null) {
				is.close();
			}
		} catch (IOException e) {
		}
	}

	public static InputStream readFile(String path) {
		InputStream is = null;
		try {
			File file = new File(path);
			if (file.exists()) {
				is = new FileInputStream(file);
			}
		} catch (Exception e) {
		}
		return is;
	}

}
